import Mock from 'mockjs'

const Random = Mock.Random

const {newList} = Mock.mock({
	"newList|9":[
		{
			name:"@cname()",
			title:"@ctitle",
			content:"@cparagraph(5,10)",
			date:"@date(yyyy-MM-dd)",
			image:Random.image('300x250','#000000','#FFFFFF','png','左宇宏')
		}
	]
})
function getQery(url,name){
	const index = url.indexOf('?');
	if(index != -1){
		const queryStr =  url.substr(index+1).split('&');
		for(let i=0;i<queryStr.length;i++){
			const itemArr = queryStr[i].split('=')
			if(itemArr[0]===name){
				return itemArr[1]
			}
		}
	}
	return null
}
let pageindex,pagesize,start,end,totalPage;
Mock.mock(/\/api\/get\/news/,'get',(options)=>{
	pageindex = getQery(options.url,'pageindex');
	pagesize = getQery(options.url,'pagesize');
	start = (pageindex-1)*pagesize;
	end = pageindex*pagesize;
	
	totalPage = Math.ceil(newList.length/pagesize);
	const list =  pageindex > totalPage ? [] : newList.slice(start,end);
	return {
		status:200,
		message:'获取新闻列表成功',
		list,
		total:newList.length,
	}
})
Mock.mock('/api/add/news','post',(options)=>{
	const body = JSON.parse(options.body).data;
	//console.log(body);
	newList.unshift(body);
	const list =  pageindex > totalPage ? [] : newList.slice(start,end);
	return {
		status:200,
		message:'添加列表成功',
		list,
		total:newList.length,
	}
})

//定义删除的接口
Mock.mock('/api/delete/news','post',(options)=>{
	let index = newList.findIndex((item)=>{
		return item.name==options.body
	})
	newList.splice(index,1)
	return {
		status:200,
		message:'删除列表成功',
		list:newList,
		total:newList.length,
	}
})
//定义编辑接口

Mock.mock(/\/api\/edit\/news/,'get',(options)=>{
	let name = decodeURIComponent(getQery(options.url,'name'));
	let res = newList.find(item=>{
		return item.name == name
	})
	return res
})
Mock.mock('/api/edit/news','post',(options)=>{
	const body = JSON.parse(options.body);
	const res = newList.findIndex(item=>{
		return item.name == body.name;
	})
	if(res != -1){newList[res]=body}
	const list =  pageindex > totalPage ? [] : newList.slice(start,end);
	return {
		status:200,
		message:'修改列表成功',
		list,
		total:newList.length,
	}
})